<?php
////////////////////////////////////////////////////////////
/*
 *
 */
include_once(CLASS_PATH."Api.php");
require_once(DATA_PATH."table_dao.php");
include_once(CLASS_PATH."GetSiteConfig.php");
class logic{
	private $action,$api,$Obj,$ApiListModel,$ApiItemModel,$ApiCategory,$ApiSortOrder;
	private $is_single_site,$sites;
	
	public function logic($request){
		$this->action = $request;
		$this->api = new Api();
	}
	/*
	* Get Search Api
	*/
	private function Get($site,$type,$is_tran=false){//$site = $this->action["site"] or $site = explode(",",$this->action["site"])[n];
		$result = $this->LoadSiteModel($site,$type,$is_tran);
		if(empty($result)){
			$operation = checknull("op", $this->action);
			if($operation=="list"){
				$check_action = checknull("q", $this->action);
				$check_failmsg = "Please input the keyword!\n";
				$model = checknull($site, $this->ApiListModel);
			}elseif($operation=="item"){
				$check_action = checknull("itemid", $this->action);
				$check_failmsg = "Please input the itemid!\n";
				$model = checknull($site, $this->ApiItemModel);
			}
			if(empty($check_action)){
				$result = $check_failmsg;
			}else{
				if($type=="shopping"&&CACHE_SHOPPING){
					$cache = true;
				}else{
					$cache = false;
				}
				if($this->Obj->IsGetApiPage){
					$result = $this->api->Get($this->Obj->GetUrl($operation),$model,$this->Obj->ApiXmlOrJson,$cache);
				}
				$this->Obj = NULL;
			}
		}
		return $result;
	}
	public function Output($operation,$format = "JSON",$is_tran=false){
		//$operation = $this->action["op"];
		$site = checknull("site", $this->action);
		$type = checknull("type", $this->action);
		$this->checksite($site);
		$result=array();
		if($operation=="list"){
			$sites = explode(",", $site);
			foreach($sites as $childsite){
				if(!empty($childsite)){
					array_push($result,$this->Get($childsite,$type,$is_tran));
				}
			}
		}elseif($operation=="item"){
			array_push($result,$this->Get($site,$type,$is_tran));
		}elseif($operation=="hotkey"){
			$apidata = $this->GetHotKey();
		}elseif($operation=="autocomplete"){
			$apidata = $this->GetAutoKey();
		}else{
			$apidata = $this->GetLangValue($operation,$site,$type,$is_tran);
		}
		
		if(empty($apidata)){
			$result["0"] = checknull("0", $result);
			if(empty($result["0"])){
				$apidata	= array();
			}else{
				$apidata = $this->FixMerge($result);
			}
			if(empty($apidata)){
				$apidata	= array(
					"Available"	=>0,
					"item"		=>array(
						"0"		=>array(),
					),
				);
			}
			//print_r($apidata	);
		}
		if($format =="XML"||$format =="JSON"){
			return $this->api->Set($apidata,$format);
		}else{
			return $apidata;
		}
	}
	private function GetHotKey(){
		$result = array();
		$key_dao = new table_dao("keywords");
		$keydata = $key_dao->get(array("orderby"=>"hits DESC"),1);
		$is_inserted = is_array($keydata)?true:false;
		if($is_inserted){
			foreach($keydata as $key=>$val)
			$result[] = checknull("Key", $val);
		}
		return $result;
	}
	private function GetAutoKey(){
		$result = array();
		$key_dao = new table_dao("keywords");
		$keydata = $key_dao->get(array("like"=> "`Key` like '".checknull("q", $this->action)."%'","orderby"=>"hits DESC"));
		$is_inserted = is_array($keydata)?true:false;
		if($is_inserted){
			foreach($keydata as $key=>$val)
			$result[] = checknull("Key", $val);
		}
		return $result;
	}
	private function LoadSiteModel($site,$type,$is_tran=false){
		$this->Obj = new GetSiteConfig($type,$site,$this->action,$is_tran,$this->is_single_site);
		if($this->Obj->IsLoadCongig&&!empty($type)&&!empty($site)){
			$this->ApiCategory[$site] = checknull($site, $this->ApiCategory);
			if(empty($this->ApiCategory[$site])){
				$this->ApiCategory[$site] = $this->Obj->ApiCategory;
				$this->ApiSortOrder[$site] = $this->Obj->ApiSortOrder;
				$this->ApiListModel[$site] = $this->Obj->ApiListModel;
				$this->ApiItemModel[$site] = $this->Obj->ApiItemModel;
			}
			return NULL;
		}else{
			return "Please input the right site(yahoo/bidders/kakaku/rakuten/amazon) or the right type(auction/shopping)!\n";
		}
	}
	private function GetNewCategory($sites,$type){
    include(CONFIG_PATH."SiteCateArray.php");
    $result = NULL;
    $childarr = array(
      "cn"=>1,
      "en"=>3,
      "tw"=>2,
      "ja"=>0,
    );
    $thelang = LANG;
    $langnum = checknull($thelang, $childarr);
    $result["_default"] = explode("|", checknull("default", $SiteCate));
    //print_r($result["_default"]);
    $result["_default"] = checknull($langnum, $result["_default"]);
		foreach($sites as $childsite){
      $thecate = checknull($childsite, checknull($type, $SiteCate));
      //print_r($SiteCate[$type]);
      if(is_array($thecate)){
        foreach($thecate as $key=>$val){
          $names = explode("|", checknull("name", $val));
          $result[$key] = checknull($langnum, $names);
        }
      }
		}
		//print_r($result);
    return $result;
	}
	private function GetLangValue($langfile,$site,$type,$is_tran=false){
    if(false==$this->is_single_site){
        $sites = array('all');
    }else{
        $sites = $this->sites;
    }
		if($langfile=="category"){
      return $this->GetNewCategory($sites,$type);
		}
		
		
		foreach($this->sites as $childsite){
			$result = $this->LoadSiteModel($childsite,$type,$is_tran);
		}
		if(empty($result)){
			$lang_path = CONFIG_LANG_PATH.LANG."/".$langfile.".php";
			if(file_exists($lang_path)){
				include_once($lang_path);
			}
			if($langfile=="category"){
				$lang_model = $this->ApiCategory;
				$lang_Value = $Lang_Category;
				//unset($Lang_Category);
			}elseif($langfile=="sortorder"){
				$lang_model = $this->ApiSortOrder;
				$lang_Value = $Lang_SortOrder;
				//unset($Lang_SortOrder);
			}elseif($langfile=="interface"){
				$this->Obj = NULL;
				return $Lang_Interface;
			}elseif($langfile=="feedback"){
				$this->Obj = NULL;
				return $Lang_Feedback;
			}else{
				return "Please input the right op(list/item/category/sortorder)";
			}
			$result=$this->FixLangModel($lang_model,$lang_Value);
		}
		$this->Obj = NULL;
		return $result;
	}
	private function checksite($site){
      preg_match_all('/\w+/',$site,$this->sites);
	    $this->is_single_site = true;
      if(is_array($this->sites)){
      	$this->sites[0] =checknull("0", $this->sites);
          if(is_array($this->sites[0])){
              $this->sites = $this->sites[0];
              foreach($this->sites as $siteolder=>$sitename){
                  foreach($this->sites as $siteolder1=>$sitename1){
                      if($siteolder1!=$siteolder&&$sitename1!=$sitename){
                          $this->is_single_site = false;
                      }
                  }
              }
          }
      }
	}
	private function FixLangModel($lang_model,$lang_Value){
		$result = NULL;
		if(is_array($lang_model)){
			foreach($lang_model as $childsite=>$childarr){
				if(is_array($childarr)){
					$lang_Value["default"] = checknull("default", $lang_Value);
					if(!empty($lang_Value["default"])){
						$result["_default"] = $lang_Value["default"];
					}
					foreach($childarr as $key=>$val){
						$result[$key] = checknull($key, $result);
						if(!empty($val)&&empty($result[$key])){
							$result[$key] = checknull($key, $lang_Value);
						}
					}
				}
			}
			/*
			if(!empty($result)){
				ksort($result);
			}
			*/
		}
		return $result;
	}
	private function FixMerge($data){
		$result=array();
		if(is_array($data)){
			foreach($data as $key=>$val){
				if(is_array($val)){
					if(in_array("Available",	array_keys($val))){
						if(0==(int)$val["Available"]){
							unset($data[$key]);
							continue;
						}
					}
					foreach($val as $akey=>$aval){
						if(is_array($aval)){
							$result[$akey] = checknull($akey, $result);
							$result[$akey] = array_merge_recursive(empty($result[$akey])?array():$result[$akey],$aval);
						}else{
							$resultakey		= checknull($akey, $result);
							$result[$akey]	= NULL;
							if($akey=="Available"){$aval = (int)$aval;}
							if(is_numeric($aval)){
								$result[$akey] = $resultakey+$aval;
							}else{
								$result[$akey] .= (empty($resultakey)?NULL:",").$aval;
							}
						}
					}
				}
			}
			$result = $this->FixSort($result);
		}
		if(empty($result)){$result=$data;}
		return $result;
	}
	private function FixSort($data){
		$result = array();
		if(is_array($data)){
			foreach($data as $key=>$val){
				if(is_array($val)){
					$action_s = checknull("s", $this->action);
					if($action_s=="end,D"){
						$orderkey = "endtime";
						$order = 1;
					}elseif($action_s=="price,A"){
						$orderkey = "price";
						$order = 0;
					}elseif($action_s=="price,D"){
						$orderkey = "price";
						$order = 1;
					}elseif($action_s=="bids,A"){
						$orderkey = "bids";
						$order = 0;
					}elseif($action_s=="bids,D"){
						$orderkey = "bids";
						$order = 1;
					}else{
						$orderkey = "endtime";
						$order = 0;
					}
					$result[$key] = $this->Contrast($val,$orderkey,$order);
				}else{
					$result[$key] = $val;
				}
			}
		}
		return $result;
	}
	private function Contrast($data,$orderkey = "endtime",$order = 0){
		$result = array();
		if(is_array($data)){
			$count = count($data)-1;
			for($i=$count;$i>=1;$i--){
				for($j=0;$j<$i;$j++){
					$data_j = checknull($j,$data);
					$data_j_orderkey = checknull($orderkey, $data_j);
					
					$data_j1 = checknull($j+1,$data);
					$data_j1_orderkey = checknull($orderkey, $data_j1);
					if($order == 0){
						if($data_j_orderkey>$data_j1_orderkey){
							$t = $data_j;
							$data[$j] = $data_j1;
							$data[$j+1] = $t;
						}
					}else{
						if($data_j_orderkey<$data_j1_orderkey){
							$t = $data_j;
							$data[$j] = $data_j1;
							$data[$j+1] = $t;
						}
					}
				}
			}
		}
		return $data;
	}
}